package com.hundsun.yr.universal.library.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.StateSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.TextView;

import com.hundsun.yr.universal.library.R;
import com.hundsun.yr.universal.library.common.DensityUtils;

/**
 * @Title: HSButton.java
 * @Description: 圆角（空心）纯色按钮
 * todo 学习
 * @date 2015-10-15 下午4:12:18
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 * @version V1.0
 */
public class HSButton extends TextView {

	private static final int DEFAULT_STROKE_WIDTH = 2;// 默认边线宽度2px
	private static final int DEFAULT_STROKE_COLOR = Color.TRANSPARENT;// 默认边线颜色
	private static final int DEFAULT_SOLID_COLOR = Color.WHITE;// 默认普通填充颜色
	private static final int DEFAULT_CORNERRADIUS = 4;// 默认圆角4dp
	private static final int DEFAULT_TEXT_COLOR = android.R.color.black;// 默认文字颜色

	private int mCornerRadius = 0;// 圆角
	private int mStrokeWidth = 0;// 边界宽度
	private int mSolidColor_n = -1;// 普通填充色
	private int mSolidColor_p = -1;// 按下填充色
	private int mStrokeColor_n = -1;// 普通边框颜色
	private int mStrokeColor_p = -1;// 按下边框颜色
	private int mTextColor_n = -1;// 普通填充色
	private int mTextColor_p = -1;// 按下填充色

	private boolean hasAttrs = false;
	private StrokeGradientDrawable mDrawableNormal;
	private StrokeGradientDrawable mDrawablePressed;
	private StrokeGradientDrawable mDrawableEnabled;
	private int DEFAULT_TOP_BOTTON = 5;
	private int DEFAULT_LEFT_RIGHT = 8;

	private boolean isCircle = false;
    private Drawable background;

    public HSButton(Context context) {
		this(context, null);
	}

	public HSButton(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public HSButton(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);

		initView(context, attrs);
	}

	public StrokeGradientDrawable getDrawableNormal() {
		return mDrawableNormal;
	}

	@Override
	public void setEnabled(boolean enabled) {
//		if (!enabled) {
//			setSolidBackground();
//			StateListDrawable background = new StateListDrawable();
//			background.addState(StateSet.NOTHING, mDrawableEnabled.getGradientDrawable());
//			setBackgroundCompat(background);
//		} else {
//			setSolidBackground();
//		}
		super.setEnabled(enabled);
		setSolidBackground();
		invalidate();
	}
	
	private int enabledColor = 0;
	/**
	 * 设置Enabled颜色
	 * @param enabledColor
	 */
	public void setEnabledColor(int enabledColor){
		
		this.enabledColor=enabledColor;
	}

	private void initView(Context context, AttributeSet attrs) {

		setClickable(true);
		setGravity(Gravity.CENTER);
		setIncludeFontPadding(false);
		int top = getPaddingTop() > 0 ? getPaddingTop() : DensityUtils.dp2px(context, DEFAULT_TOP_BOTTON);
		int left = getPaddingLeft() > 0 ? getPaddingLeft() : DensityUtils.dp2px(context, DEFAULT_LEFT_RIGHT);
		int right = getPaddingRight() > 0 ? getPaddingRight() : DensityUtils.dp2px(context, DEFAULT_LEFT_RIGHT);
		int bottom = getPaddingBottom() > 0 ? getPaddingBottom() : DensityUtils.dp2px(context, DEFAULT_TOP_BOTTON);

		setPadding(left, top, right, bottom);

		if (null != attrs) {
			TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HSButton);

			if (a.hasValue(R.styleable.HSButton_sb_color_n)) {
				mSolidColor_n = a.getColor(R.styleable.HSButton_sb_color_n, DEFAULT_SOLID_COLOR);
				hasAttrs = true;
			}

			if (a.hasValue(R.styleable.HSButton_sb_color_p)) {
				mSolidColor_p = a.getColor(R.styleable.HSButton_sb_color_p, DEFAULT_SOLID_COLOR);
				hasAttrs = true;
			}

			if (a.hasValue(R.styleable.HSButton_sb_storke_color_n)) {
				mStrokeColor_n = a.getColor(R.styleable.HSButton_sb_storke_color_n, DEFAULT_STROKE_COLOR);
				hasAttrs = true;
				mStrokeWidth = DEFAULT_STROKE_WIDTH;
			}

			if (a.hasValue(R.styleable.HSButton_sb_storke_color_p)) {
				mStrokeColor_p = a.getColor(R.styleable.HSButton_sb_storke_color_p, DEFAULT_STROKE_COLOR);
				hasAttrs = true;
				mStrokeWidth = DEFAULT_STROKE_WIDTH;
			}

			if (a.hasValue(R.styleable.HSButton_sb_corners)) {
				mCornerRadius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, a.getDimension(R.styleable.HSButton_sb_corners, DEFAULT_CORNERRADIUS), getResources().getDisplayMetrics());
			}

			if (a.hasValue(R.styleable.HSButton_sb_storke)) {
				mStrokeWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, a.getDimension(R.styleable.HSButton_sb_storke, DEFAULT_STROKE_WIDTH), getResources().getDisplayMetrics());
			}

			if (a.hasValue(R.styleable.HSButton_sb_textcolor_n)) {
				mTextColor_n = a.getColor(R.styleable.HSButton_sb_textcolor_n, DEFAULT_TEXT_COLOR);
			}

			if (a.hasValue(R.styleable.HSButton_sb_textcolor_p)) {
				mTextColor_p = a.getColor(R.styleable.HSButton_sb_textcolor_p, DEFAULT_TEXT_COLOR);

			}

			if (a.hasValue(R.styleable.HSButton_sb_circle)) {
				isCircle = a.getBoolean(R.styleable.HSButton_sb_circle, false);
				if (isCircle)
					setPadding(0, top, 0, bottom);
			}

			if (getBackground() != null){
                background = getBackground();
            }

			a.recycle();

			setTextCompat();

			if (hasAttrs) {
				setSolidBackground();
			}

		}

	}

	/**
	 * 设置背景颜色
	 */
	private void setSolidBackground() {
//		if (!(mSolidColor_n == -1 && mSolidColor_p == -1 && mStrokeColor_n == -1 && mStrokeColor_p == -1)) {

			if (mSolidColor_n != -1 && mSolidColor_p == -1) {
				mSolidColor_p = mSolidColor_n;
			} else if (mSolidColor_n == -1 && mSolidColor_p != -1) {
				mSolidColor_n = mSolidColor_p;
			} else if (mSolidColor_n == -1 && mSolidColor_p == -1) {
				mSolidColor_n = DEFAULT_SOLID_COLOR;
				mSolidColor_p = DEFAULT_SOLID_COLOR;
			}
			if (mStrokeColor_n != -1 && mStrokeColor_p == -1) {
				mStrokeColor_p = mStrokeColor_n;
			} else if (mStrokeColor_n == -1 && mStrokeColor_p != -1) {
				mStrokeColor_n = mStrokeColor_p;
			} else if (mStrokeColor_n == -1 && mStrokeColor_p == -1) {
				mStrokeColor_n = DEFAULT_STROKE_COLOR;
				mStrokeColor_p = DEFAULT_STROKE_COLOR;
			}

			StateListDrawable background = new StateListDrawable();
			mDrawableNormal = createDrawable(mSolidColor_n, mCornerRadius, mStrokeColor_n, mStrokeWidth);
			mDrawablePressed = createDrawable(mSolidColor_p, mCornerRadius, mStrokeColor_p, mStrokeWidth);
			if(enabledColor==0){
				mDrawableEnabled = createDrawable(getResources().getColor(R.color.enabled_color), mCornerRadius, android.R.color.transparent, 0);
			} else{
				mDrawableEnabled = createDrawable(enabledColor, mCornerRadius, android.R.color.transparent, 0);
			}
			if (!isEnabled()) {
				background.addState(StateSet.NOTHING, mDrawableEnabled.getGradientDrawable());
				setBackgroundCompat(background);
			} else {
				if (mSolidColor_n == DEFAULT_SOLID_COLOR && mSolidColor_p == DEFAULT_SOLID_COLOR && mStrokeColor_n == DEFAULT_STROKE_COLOR && mStrokeColor_p == DEFAULT_STROKE_COLOR){
					setBackgroundCompat(this.background);
				} else {
					background.addState(new int[] { android.R.attr.state_pressed }, mDrawablePressed.getGradientDrawable());
					background.addState(StateSet.WILD_CARD, mDrawableNormal.getGradientDrawable());
					setBackgroundCompat(background);
				}
			}

//		}
	}

	/**
	 * 设置文字颜色
	 */
	private void setTextCompat() {

		if (mTextColor_n != -1 && mTextColor_p != -1) {
			int statePressed = android.R.attr.state_pressed;
			int stateFocesed = android.R.attr.state_focused;
			int[][] state = { { statePressed }, { -statePressed }, { stateFocesed }, { -stateFocesed } };

			int color_n = mTextColor_n;
			int color_p = mTextColor_p;
			int[] color = { color_p, color_n ,color_p, color_n};
			ColorStateList colorStateList = new ColorStateList(state, color);
			setTextColor(colorStateList);
		} else if (mTextColor_n != -1 && mTextColor_p == -1) {
			setTextColor(mTextColor_n);
		} else if (mTextColor_n == -1 && mTextColor_p != -1) {
			setTextColor(mTextColor_p);
		}

	}

	/**
	 * 含边框
	 * 
	 * @param color
	 * @param cornerRadius
	 * @param strokeColor
	 * @param strokeWidth
	 * @return
	 */
	private StrokeGradientDrawable createDrawable(int color, int cornerRadius, int strokeColor, int strokeWidth) {
		final StrokeGradientDrawable drawable = new StrokeGradientDrawable(new GradientDrawable());
		drawable.getGradientDrawable().setShape(GradientDrawable.RECTANGLE);
		drawable.setColor(color);
		drawable.setStrokeColor(strokeColor);
		drawable.setStrokeWidth(strokeWidth);

		if (isCircle) {
			new Handler().post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					drawable.setCornerRadius(getHeight() / 2);
				}
			});
		} else {
			drawable.setCornerRadius(cornerRadius);
		}
		return drawable;

	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	private void setBackgroundCompat(@Nullable Drawable drawable) {
		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
			setBackgroundDrawable(drawable);
		} else {
			setBackground(drawable);
		}
	}

	public void setIcon(@DrawableRes final int icon) {
		// post is necessary, to make sure getWidth() doesn't return 0
		post(new Runnable() {
			@SuppressWarnings("deprecation")
			@Override
			public void run() {
				Drawable drawable = getResources().getDrawable(icon);
				int padding = (getWidth() / 2) - (drawable.getIntrinsicWidth() / 2);
				setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
				setPadding(padding, 0, 0, 0);
			}
		});
	}

	public void setIconLeft(@DrawableRes int icon) {
		setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
	}

}